import log4js = require('log4js');
import path = require("path");
import fs = require("fs");
import { ICleanService } from '../dataClean/cleanManager';

const webconfig = require("../../../webconfig").webconfig;
let moment = require('moment');

export class Logger implements ICleanService {
    //客户端ip |请求地址 |请求方法 |HTTP版本 |请求状态 |响应时间 |请求来源 |请求内容大小 |浏览器ua
    private logFormat = [':remote-addr', ':url', ':method', ':http-version', ':status', ':response-time', ':referrer', ':content-length', ':user-agent'];
    private logPath = webconfig.logRootDir;
    constructor() {
        //配置日志信息
        log4js.configure({
            //配置app日志、访问日志、错误日志
            appenders: [
                { type: 'console' },
                this.appender('app', true),
                this.appender('access', true),
                this.appender('error', true)
            ],
            // levels: {
            //     "error": "ERROR"
            // },
            // replaceConsole: true
        });
    }

    get ServiceName() {
        return "Logger";
    }

    CleanData() {
        let log = new Logger().getLogger("app");
        // 读取当前日志目录下的所有文件名
        // 先检查目录是否存在
        if (fs.existsSync(this.logPath)) {
            // 筛选出 3 天前的日志并删除，目前通过文件名来匹配，可以考虑通过文件修改/创建时间来匹配
            let reg = new RegExp(/[1-2][0-9][0-9][0-9]-[0-1]{0,1}[0-9]-[0-3]{0,1}[0-9]|[1-2][0-9][0-9][0-9][0-1]{0,1}[0-9][0-3]{0,1}[0-9][0-2][0-9]/);
            let files = fs.readdirSync(this.logPath);
            let startTime = moment().subtract(3, 'day').valueOf();
            let count: number = 0;
            for (let file of files) {
                try {
                    let dateString: any = file.match(reg);
                    if (dateString && dateString.length > 0) {
                        dateString = dateString[0];
                    } else {
                        continue;
                    }
                    // 目前只清除 access 和 error
                    if (!(file.indexOf('access') >= 0 || file.indexOf('error') >= 0)) continue;
                    let format: string = 'YYYYMMDD';
                    if (dateString.indexOf('-') >= 0) {
                        format = 'YYYY-MM-DD';
                    } else if (dateString.length === 8) {
                        dateString = [dateString, '00'].join('');
                    }
                    let fileCreatedTime = moment(dateString, format).valueOf();
                    if (startTime > fileCreatedTime) {
                        fs.unlinkSync([this.logPath, '/', file].join(''));
                        count++;
                    }
                } catch (err) {
                    continue;
                }
            }
            log.info([
                "日志清理完成，共清理了 ",
                count,
                " 个日志文件=============================="].join('')
            );
        } else {
            log.error('日志目录不存在==============================');
        }
    }

    //日志类型
    private appender(logName: string, isWorker?: boolean) {
        let logId = '';
        let dateString = moment().format('YYYY-MM-DD');
        if (isWorker) {
            logId = (process.env.workerUID && process.env.workerUID.toString()) || "1";
        }
        return {
            type: 'file',
            absolute: true,
            filename: path.join(this.logPath, logName + logId + '-' + dateString + '.log'),
            maxLogSize: 1024 * 1024,
            backup: 3,
            pattern: "-yyyy-MM-dd.log",
            alwaysIncludePattern: true,
            category: logName
        }
    };

    getLogger(logName) {
        return log4js.getLogger(logName);
    }

    logConnect(logName, format) {
        let logger = this.getLogger(logName);

        //设置level为auto，遇到4xx和5xx会自动记录error级日志
        let logPattern = {
            level: 'auto',
            format: format || this.logFormat.join(' |')
        };
        return log4js.connectLogger(logger, logPattern);
    }

    deleteLogFile() {
        //fs.stat()
    }
}